const baseURL = 'https://api.example.com' // 替换为你的实际接口地址

// 请求拦截器
const requestInterceptor = (options) => {
  options.url = baseURL + options.url
  options.header = {
    ...options.header,
    'content-type': 'application/json'
  }
  
  // 获取token
  const token = uni.getStorageSync('token')
  if (token) {
    options.header.Authorization = `Bearer ${token}`
  }
  
  return options
}

// 响应拦截器
const responseInterceptor = (response) => {
  const { statusCode, data } = response
  
  if (statusCode >= 200 && statusCode < 300) {
    return data
  }
  
  if (statusCode === 401) {
    // token过期，跳转登录页
    uni.navigateTo({
      url: '/pages/login/login'
    })
    return Promise.reject(new Error('请先登录'))
  }
  
  return Promise.reject(response)
}

// 封装请求方法
const request = (options) => {
  options = requestInterceptor(options)
  
  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      success: (res) => {
        resolve(responseInterceptor(res))
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

 